package com.example.cybz.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cybz.acl.mapper.PermissionMapper;
import com.example.cybz.acl.service.RolePermissionService;
import com.example.cybz.acl.utils.PermissionHelper;
import com.example.cybz.model.acl.Permission;
import com.example.cybz.model.acl.RolePermission;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements com.example.cybz.acl.service.PermissionService {

    private final RolePermissionService rolePermissionService;

    /**
     * 查询所有权限信息
     * 该方法会获取所有权限数据，并通过PermissionHelper构建权限树结构
     * 
     * @return 返回构建好的权限树列表
     */
    @Override
    public List<Permission> queryAllPermission() {
        List<Permission> list = new LambdaQueryChainWrapper<>(baseMapper)
                .list();

        List<Permission> result = PermissionHelper.buildPermission(list);
        return result;
    }

    /**
     * 删除指定ID及其所有子权限
     * 递归查询所有子权限ID并删除
     * 
     * @param id 需要删除的权限ID
     * @return 删除操作是否成功
     */
    @Override
    public boolean removeChildById(Long id) {
        if (id == null) {
            return false;
        }

        List<Long> idList = new ArrayList<>();
        idList.add(id);
        // 递归查询所有子权限ID
        queryAllPermissionId(id, idList);

        if (idList.isEmpty()) {
            return true;
        }

        return removeByIds(idList);
    }

    /**
     * 保存角色与权限的关联关系
     * 先删除角色原有权限，再保存新的权限关联
     * 
     * @param roleId 角色ID
     * @param permissionList 权限ID列表
     * @return 返回操作是否成功
     */
    @Override
    public boolean savaPermissionRole(Long roleId, List<Long> permissionList) {
        boolean remove = rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, roleId));
        if (remove){
            // 查询权限信息并构建角色权限关联对象列表
            List<RolePermission> collect = new LambdaQueryChainWrapper<>(baseMapper).in(Permission::getId, permissionList)
                    .list()
                    .stream()
                    .map(permission -> new RolePermission(roleId, permission.getId()))
                    .collect(Collectors.toList());
            return rolePermissionService.saveBatch(collect);
        }
        return false;
    }

    /**
     * 递归查询所有子权限ID
     * 用于删除操作时收集所有需要删除的权限ID
     * 
     * @param id 当前处理的权限ID
     * @param idList 存储需要删除的所有权限ID的列表
     */
    private void queryAllPermissionId(Long id, List<Long> idList) {
        // 查询当前ID下的直接子权限
        List<Permission> permissions = new LambdaQueryChainWrapper<>(getBaseMapper())
                .eq(Permission::getPid, id)
                .list();

        for (Permission permission : permissions) {
            if (!idList.contains(permission.getId())) { // 防止循环引用
                idList.add(permission.getId());
                // 递归查询下一级子权限
                queryAllPermissionId(permission.getId(), idList);
            }
        }
    }
}
